//
//  ViewController.swift
//  表情字符串
//
//  Created by zhangguo on 15/10/26.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
       let string = "我[爱你]啊[笑哈哈]"
        
        
        label.attributedText = EmoticonsPackage.emoticonText(string, font: label.font)
        
//       print(EmoticonsPackage.emoticon(string: "[爱你]"))
//          print(EmoticonsPackage.emoticon(string: "[笑哈哈]"))
        //正则表达式 []是正则表达式的关键字，需要\\转义
        let pattern = "\\[.*?\\]"
        let regex = try!NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
        
        //开始匹配
        let results = regex.matchesInString(string, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0,string.characters.count))
        
        //获得匹配结果
        var count = results.count
        
        //使用string创建属性文本
        let strM = NSMutableAttributedString(string: string)
        
        //到这遍历数组，获取匹配结果
        while count > 0 {
            let result = results[--count]
            let range = result.rangeAtIndex(0)
            
            //获取到表情字符串
            let emString = (string as NSString).substringWithRange(range)
            
            if let emoticon = EmoticonsPackage.emoticon(string: emString) {
            //根据表情，穿件属性字符串
            let attrString = EmoticonAttachment.imageText(emoticon, font: label.font)
                
              //替换strM中对应位置的文本
                strM.replaceCharactersInRange(range, withAttributedString: attrString)
            }
         
        }
        label.attributedText = strM
        
    }
    private func emoticon(string string: String) -> Emoticon? {
        
       
        //遍历所有的表情包的表情数组
        var emoticon:Emoticon? = nil
        for p in EmoticonsPackage.packages  {
            
            //在p emoticons数组中查找表情
            emoticon = p.emoticons?.filter{($0.chs == string)}.last
            
            //如果找到emoticon就退出
            
            if emoticon != nil {
                break
            }
        }
        return emoticon
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

